package org.hockeystats.repository.internal;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hockeystats.domain.Player;
import org.hockeystats.repository.PlayerRepository;
import org.springframework.stereotype.Service;

@Service
public class PlayerRepositoryImpl implements PlayerRepository {

	@PersistenceContext
	EntityManager entityManager;
	
	public void addPlayer(Player player) {
		entityManager.persist(player);
		entityManager.flush();
		entityManager.clear();
	}

	public Player findPlayer(long id) {
		Criteria criteria = ((Session)entityManager.getDelegate()).createCriteria(Player.class);
		criteria.add(Restrictions.eq("id", id));
		Player player = (Player)criteria.uniqueResult(); 
		return player;
	}

	@SuppressWarnings("unchecked")
	public List<Player> findAllPlayers() {
		Criteria criteria = ((Session)entityManager.getDelegate()).createCriteria(Player.class);
		return criteria.list();
	}

	public void removePlayer(Player player) {
		entityManager.remove(player);
		entityManager.flush();
		entityManager.clear();
	}
}